import axios from "axios";
import { getToken } from "@/utils/common";
import { Loading, Message, Notification, MessageBox } from "element-ui";
import FileSaver from "file-saver";
const baseUrl = process.env.VUE_APP_BASE_API;
// 导入模板下载路径
const downloadTmplUrl = "/file/base/common/download/configkey/";

// 通用文件下载路径
const downloadFileUrl = "/file/base/common/download/id/";

// 文件名下载
const downloadFileNameUrl = "/base/common/download/name";

const mimeMap = {
  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  zip: "application/zip",
  pdf: "application/pdf",
};
const request = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时时长设置
  timeout: 600000,
  // 响应类型
  responseType: "blob",
});

export function downloadById(fileId) {
  if (fileId) {
    request
      .get(downloadFileUrl + fileId, {
        headers: { Authorization: "Bearer " + getToken() },
      })
      .then((res) => {
        if (res.headers["content-type"] === "application/json;charset=UTF-8") {
          const reader = new FileReader();
          reader.readAsText(res.data);
          reader.onload = function () {
            const resp = JSON.parse(reader.result);
            Notification.error({
              title: resp.code + " 错误",
              message: resp.msg,
              duration: 0,
            });
          };
        } else {
          const desc = res.headers["content-disposition"];
          const filename = desc.substring(desc.indexOf("=") + 1, desc.length);
          const blob = new Blob([res.data], {
            type: "application/octet-stream",
          });
          FileSaver.saveAs(blob, decodeURIComponent(filename));
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }
}

/**
 * 自定义下载方法
 * @param url
 * @param query
 * @returns {AxiosPromise}
 */
export function customDownload(url, query) {
  return axios({
    method: "get",
    url: baseUrl + url,
    params: query,
    responseType: "blob",
    headers: { Authorization: "Bearer " + getToken() },
  });
}

/**
 * 通用压缩文件下载方法
 * @param url
 * @param fileName
 */
export function downLoadZip(url, fileName) {
  axios({
    method: "get",
    url: baseUrl + url,
    responseType: "blob",
    headers: { Authorization: "Bearer " + getToken() },
  }).then((res) => {
    resolveBlob(res, mimeMap.zip, (fileName || "defaultName") + ".zip");
  });
}

/**
 * 通用压缩文件下载方法(post方式)
 * @param url
 * @param fileName
 */
export function downLoadZipPost(url, fileName, data) {
  axios({
    method: "post",
    url: baseUrl + url,
    data: data,
    responseType: "blob",
    headers: { Authorization: "Bearer " + getToken() },
  }).then((res) => {
    resolveBlob(res, mimeMap.zip, (fileName || "defaultName") + ".zip");
  });
}

/**
 * 通用pdf文件下载方法(post方式)
 * @param url
 * @param fileName
 */
export function downLoadPdfPost(url, fileName, data) {
  axios({
    method: "post",
    url: baseUrl + url,
    data: data,
    responseType: "blob",
    headers: { Authorization: "Bearer " + getToken() },
  }).then((res) => {
    resolveBlob(res, mimeMap.pdf, (fileName || "defaultName") + ".pdf");
  });
}

/**
 * 导出报表方法获取默认的industryCode
 * @returns
 */
const getDefaultIndustryCode = () => {
  let industryCode = "";
  if (sessionStorage.getItem("chooseTradeVersiondd2")) {
    const e = sessionStorage.getItem("chooseTradeVersiondd2");
    industryCode = e;
  } else {
    let p = sessionStorage.getItem("chooseTradeVersiondd");
    if (p) {
      p = JSON.parse(p);
      industryCode = p && p.industryCode ? p.industryCode : "";
    }
  }
  return industryCode;
};

/**
 * 通用表格信息导出方法
 * @param url
 * @param query
 * @param fileName
 */
export function exportExcel(url, query, fileName) {
  MessageBox.confirm("是否确认导出所有的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const loadingInstance = Loading.service({
        lock: true,
        text: "数据正在准备中，请稍等...",
        background: "rgba(0, 0, 0, 0.7)",
      });

      let industryCode = "";
      if (url && url == "/auth/chooseTrade") {
        const p = sessionStorage.getItem("chooseTradeVersionddw");
        if (p) {
          industryCode = p;
        }
      } else {
        industryCode = getDefaultIndustryCode();
      }
      axios({
        method: "post",
        url: baseUrl + url,
        data: query,
        responseType: "blob",
        headers: {
          Authorization: "Bearer " + getToken(),
          "Cur-Industry-Code": industryCode,
        },
      })
        .then((res) => {
          loadingInstance.close();
          if (
            res.data.type == "application/octet-stream" ||
            res.data.type == "text/xml"
          ) {
            resolveBlob(res, mimeMap.xlsx, (fileName || "导出文件") + ".xlsx");
          } else {
            const reader = new FileReader();
            reader.readAsText(res.data);
            reader.onload = function () {
              const resp = JSON.parse(reader.result);
              if (resp.code == 200) {
                Message.warning(resp.msg);
              } else {
                $message.a(resp);
              }
            };
          }
        })
        .catch(() => {
          loadingInstance.close();
          Message.warning("导出失败，请检查网络");
        });
    })
    .catch(() => {
      console.log("导出所有的数据项调用异常");
    });
}

export function exportTmpl(type) {
  customDownload(downloadTmplUrl + type)
    .then((res) => {
      // debugger
      if (res.status == 200) {
        Message.success("下载成功");
        resolveBlob2(res, mimeMap.xlsx);
      } else {
        Message.warning("模板下载失败");
      }
    })
    .catch(() => {
      Message.warning("导出失败，请检查网络");
    });
}

/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 * @param {String} fileName 文件名
 */
export function resolveBlob(res, mimeType, fileName) {
  const aLink = document.createElement("a");
  const blob = new Blob([res.data], { type: mimeType });
  aLink.href = URL.createObjectURL(blob);
  aLink.setAttribute("download", fileName); // 设置下载文件名称
  aLink.setAttribute("style", "display:none;"); // 设置a标签样式
  document.body.appendChild(aLink);
  aLink.click();
  document.body.removeChild(aLink);
}

/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export function resolveBlob2(res, mimeType) {
  const aLink = document.createElement("a");
  const desc = res.headers["content-disposition"];
  const filename = desc.substring(desc.indexOf("=") + 1, desc.length);
  aLink.setAttribute("download", decodeURIComponent(filename)); // 设置下载文件名称
  const blob = new Blob([res.data], { type: mimeType });
  aLink.href = URL.createObjectURL(blob);
  document.body.appendChild(aLink);
  aLink.click();
  document.body.removeChild(aLink);

  // FileSaver.saveAs(blob, filename ? decodeURIComponent(filename) : '导入模板.xlsx');
}

/**
 *
 * 根据文件url下载文件
 */

export const downloadByUrl = async (url, fileName) => {
  try {
    // const res = await axios.get(url + `&_random=${new Date().valueOf()}`, { responseType: 'blob',contentType:'application/octet-stream' })
    // FileSaver.saveAs(res.data, fileName || '文件')
    axios({
      url: baseUrl + "/file/common/downloadByUrl",
      method: "get",
      params: {
        url: url,
      },
      headers: {
        Authorization: "Bearer " + getToken(),
      },
    }).then((res) => {
      FileSaver.saveAs(b64toBlob(res.data.data), fileName || "文件");
    });
  } catch (e) {
    Message.error("文件下载失败");
  }
};
/** */
export const downloadByName = async (fileName) => {
  try {
    const res = await axios.get(
      baseUrl + downloadFileNameUrl + "?fileName=" + fileName,
      { responseType: "blob" }
    );
    FileSaver.saveAs(res.data, fileName || "文件");
  } catch (e) {
    Message.error("文件下载失败");
  }
};

export const b64toBlob = (b64Data, contentType = "", sliceSize = 512) => {
  const byteCharacters = window.atob(b64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }

  const blob = new Blob(byteArrays, { type: contentType });
  return blob;
};
